package com.shchekoldin.server.service;

import com.shchekoldin.server.Application;
import com.shchekoldin.server.dto.MercurialBranchDto;
import com.shchekoldin.server.util.Configuration;
import org.swift.common.soap.jira.JiraSoapService;
import org.swift.common.soap.jira.JiraSoapServiceServiceLocator;
import org.swift.common.soap.jira.RemoteIssue;

import java.text.MessageFormat;
import java.util.List;

public class JiraService {

    private static final int ISSUES_MAX_RESULTS = 1000;

    public static final JiraService INSTANCE = new JiraService();

    // -------------------------------------------------------
    // LOGIC
    // -------------------------------------------------------

    private String stringifyBranches(List<MercurialBranchDto> branches) {
        StringBuilder result = new StringBuilder();
        
        for (MercurialBranchDto branch : branches) {
            if (branch.isKeyValid()) {
                result.append(branch.getKey()).append(",");
            }
        }
        
        return result.deleteCharAt(result.length() - 1).toString();
    }
    
    private JiraService() {
    }

    //
    // API
    //

    public RemoteIssue[] run(List<MercurialBranchDto> branches) throws Exception {
        Configuration config = Application.getConfiguration();

        JiraSoapServiceServiceLocator serviceLocator = new JiraSoapServiceServiceLocator();

        serviceLocator.setJirasoapserviceV2EndpointAddress(config.getJiraEndpoint());
        serviceLocator.setMaintainSession(true);

        JiraSoapService service = serviceLocator.getJirasoapserviceV2();
        String token = service.login(config.getJiraUsername(), config.getJiraPassword());
        String issuesKeys = stringifyBranches(branches);

        return service.getIssuesFromJqlSearch(
            token,
            MessageFormat.format("project = BUMP and id in ({0})", issuesKeys),
            ISSUES_MAX_RESULTS
        );
    }

}
